package com.example.demo.leetcode.classics150;

import java.util.HashMap;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _60复制带随机指针的链表
 * @description
 * @date 2023/07/27 15:58
 * <p>
 * ******************************************************
 */
public class _60复制带随机指针的链表 {

    public Node copyRandomList(Node head) {
        Map<Node, Node> oldToNew = new HashMap<>();


        Node q = head;
        Node dummy = new Node(-1);
        Node p = dummy;

        while (q != null) {
            Node newNode = oldToNew.get(q);
            if (newNode == null) {
                newNode = new Node(q.val);
                oldToNew.put(q, newNode);
            }
            if (q.random != null) {
                Node newRandomNode = oldToNew.get(q.random);
                if (newRandomNode == null) {
                    newRandomNode = new Node(q.random.val);
                    oldToNew.put(q.random, newRandomNode);
                }
                newNode.random = newRandomNode;
            }
            p.next = newNode;
            p = p.next;
            q = q.next;


        }


        return dummy.next;
    }


    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}
